package com.danbay.cloud.lock.device.service;

import com.danbay.cloud.deviceaccess.api.dto.lock.NewPwd;
import com.danbay.cloud.lock.device.client.DeviceAccessClient;
import com.danbay.cloud.lock.device.constant.LockPwdConstant;
import com.danbay.cloud.lock.device.entity.LockPrePassword;
import com.danbay.cloud.lock.device.mapper.LockPrePasswordMapper;
import com.danbay.framework.exception.BusinessException;
import com.danbay.framework.utils.RandomUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 预置密码服务层
 * @author yangyanchen on 2017/12/26
 *         Copyright © 2016 －2017 旦倍科技
 */
@Slf4j
@Service
public class LockPrePasswordService {


    @Autowired
    private LockPrePasswordMapper lockPrePasswordMapper;

    @Autowired
    private DeviceInfoCacheService deviceInfoCacheService;

    @Autowired
    private DeviceAccessClient deviceAccessClient;

    /**
     * 关于随机生成密码别名与随机生成密码的说明:
     *     1.随机生成密码别名:门锁上的密码别名要求不能重复,即存在重复的密码别名是不能添加成功的.
     *     2.随机生成密码:门锁上报的密码是允许重复的,但云端并不能获取门锁上添加的密码,即判断是否
     *   有重复的密码生成是存在歧义的.这一点待后续完善.
     * @param deviceId
     * @param pwdType
     */
    public void prePassword(String deviceId,String pwdType) throws BusinessException{
        String pwdAlias = RandomUtils.getLengthNum(8);
        String pwd = RandomUtils.getLengthNum(8);
        //下发密码的逻辑.
        LockPrePassword lockPrePassword = LockPrePassword.builder()
                                    .create_time(new Date())
                                    .update_time(new Date())
                                    .delete_state(false)
                                    .home_id(0L)
                                    .dev_id(deviceId)
                                    .psw_alias(pwdAlias)
                                    .psw_type(pwdType)
                                    .psw_value(pwd)
                                    .psw_goal(LockPwdConstant.LOCK_PRE_PASSWORD_OPERATING)
                                    .start_time(new Date())
                                    .end_time(new Date())
                                    .psw_mobile("")
                                    .device_use_state(false)
                                    .build();
        lockPrePasswordMapper.insert(lockPrePassword);
        //如何保存相应的缓存信息,则说明缓存信息要保存两份,就是一次获取即可
        deviceInfoCacheService.setLockPrePassword(deviceId,lockPrePassword);
        //下发指令
        deviceAccessClient.addNewPwd(NewPwd.builder()
                                           .alias(pwdAlias)
                                           .type(Integer.parseInt(pwdType))
                                           .pwd(pwd)
                                           .build(),deviceId);
    }

}
